<template>
	<view>
		<!-- 弹窗遮罩 -->
		<view v-if="show" class="popup-mask" @tap="close"></view>

		<!-- 弹窗内容 -->
		<view v-if="show" class="popup-container" :class="{ 'popup-show': show }">
			<view class="popup-content">
				<!-- 标题 -->
				<view class="popup-header">
					<text class="popup-title">{{ title }}</text>
					<uni-icons type="close" size="24" color="#999" @click="close" class="close-icon"></uni-icons>
				</view>

				<!-- 信息展示区域 -->
				<view class="info-section" v-if="infoData">
					<!-- 基本信息 -->
					<view class="info-group">
						<text class="info-label">物料编号:</text>
						<text class="info-value">{{ infoData.subMaterialId || '-' }}</text>
					</view>
					<view class="info-group">
						<text class="info-label">物料名称:</text>
						<text class="info-value">{{ infoData.materialName || '-' }}</text>
					</view>
					<view class="info-group">
						<text class="info-label">物料规格:</text>
						<text class="info-value">{{ infoData.subMaterialSpec || '-' }}</text>
					</view>
					<view class="info-group">
						<text class="info-label">物料类型:</text>
						<text class="info-value">{{ infoData.materialType || '-' }}</text>
					</view>

					<!-- 数量信息 -->
					<view class="info-divider"></view>

					<!-- 当前称重显示 -->
					<view class="info-group-w">
						<text class="info-label">当前称重:</text>
						<view class="info-value" :class="{ 'info-value-s': !adminUser, 'info-value-w': adminUser }">
							<text class="info-value_aa" v-if="showTos">
								{{showTos}}
							</text>
							{{ WeightStr(infoData.unitId) }}
						</view>

					</view>
					<view class="info-group-input">
						<text class="info-label">手动输入称重:</text>
						<view class="input-container">
							<input class="weight-input" type="text" :value="manualWeight" @input="onManualWeightInput"
								placeholder="请输入重量" placeholder-class="input-placeholder" :focus="autoFocus" />
						</view>
					</view>
					<!-- 授权用户信息 -->
					<view class="empty-state-c" v-if="!adminUser">
						<!-- 用户选择区域 -->
						<view class="info-group">
							<text class="info-label-u">授权用户:</text>
							<view class="user-select-container">
								<picker class="user-picker" @change="onUserChange" :value="userIndex"
									:range="userDisplayList" :disabled="userList.length === 0">
									<view class="picker-text">
										{{ selectedUser.userName ? getUserDisplayText(selectedUser) : (userList.length === 0 ? '加载中...' : '请选择用户') }}
									</view>
								</picker>
								<uni-icons type="arrowdown" size="16" color="#007AFF" class="dropdown-icon"></uni-icons>
							</view>
						</view>

						<view class="info-group-input">
							<text class="info-label">密码:</text>
							<view class="input-container">
								<input class="weight-input" type="password" :value="localPassword"
									@input="onPasswordInput" placeholder="请输入确认密码" placeholder-class="input-placeholder"
									:disabled="!selectedUser.userId" />
							</view>
						</view>
					</view>

					<!-- 状态信息 -->
					<view class="info-divider"></view>
					<view class="info-group" v-if="infoData.intervalTime">
						<text class="info-label">间隔时间:</text>
						<text class="info-value">{{ infoData.intervalTime || 0 }} 小时</text>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else>
					<uni-icons type="info" size="48" color="#ccc"></uni-icons>
					<text class="empty-text">暂无数据</text>
				</view>

				<!-- 按钮组 -->
				<view class="button-group">
					<button class="btn btn-cancel" @click="close">
						{{ cancelText }}
					</button>
					<button class="btn btn-confirm" @click="confirm" v-if="adminUser"
						:disabled="!hasWeightData || (!adminUser && !isUserValid)"
						:class="{ 'btn-disabled': !hasWeightData || (!adminUser && !isUserValid) }">
						{{ confirmText }}
					</button>


					<button class="btn btn-confirm-s" @click="confirm_status" v-if="!adminUser"
						:disabled="!hasWeightData || (!adminUser && !isUserValid)"
						:class="{ 'btn-disabled': !hasWeightData || (!adminUser && !isUserValid) }">
						{{ confirmText }}
					</button>

				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getAllocatedList
	} from '../api/system/user';

	export default {
		name: "showInfoPop",
		props: {
			// 是否显示弹窗
			show: {
				type: Boolean,
				default: false
			},
			// 弹窗标题
			title: {
				type: String,
				default: '物料信息'
			},
			// 弹窗标题
			showTosdata: {
				type: [String, null],
				default: ''
			},
			// 取消按钮文字
			cancelText: {
				type: String,
				default: '关闭'
			},
			user: {
				type: Boolean,
				default: false
			},
			// 确认按钮文字
			confirmText: {
				type: String,
				default: '确定'
			},
			// 信息数据
			infoData: {
				type: Object,
				default: () => ({})
			},
			// 是否自动聚焦输入框
			autoFocus: {
				type: Boolean,
				default: true
			},
			userInfo: {
				type: Object,
				default: () => ({
					userName: '',
					passWord: ''
				})
			},
			// 是否实时更新Vuex中的重量值
			realtimeUpdate: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				showTos: '',
				manualWeight: '', // 手动输入的重量
				localPassword: '', // 本地密码，用于双向绑定
				userIndex: 0, // 当前选中的用户索引
				selectedUser: {}, // 当前选中的用户
				userList: [], // 从接口获取的用户列表
				loading: false // 加载状态
			}
		},
		computed: {
			userDisplayList() {
				return this.userList.map(user => this.getUserDisplayText(user));
			},

			// 是否显示尺寸信息
			adminUser() {
				return this.user
			},
			// 从 weight store 获取重量值






			// 从 weight store 获取重量值
			Weight() {
				return this.$store.state.weight.weight;
			},

			// 是否有重量数据（当前称重或手动输入）
			hasWeightData() {
				return this.Weight > 0 || this.manualWeight !== '';
			},

			// 最终使用的重量值（优先使用手动输入）
			finalWeight() {
				return this.manualWeight !== '' ? this.manualWeight : this.Weight;
			},

			// 检查用户信息是否有效
			isUserValid() {
				if (this.adminUser) return true; // 管理员不需要用户验证
				return this.selectedUser && this.selectedUser.userId && this.localPassword;
			}
		},
		watch: {

			show(newVal) {
				if (newVal) {
					// 弹窗显示时重置手动输入和密码
					this.manualWeight = '';
					this.localPassword = this.userInfo.passWord || '';
					// 如果不是管理员用户，则获取用户列表
					this.queryAllocatedList();
				}
			},

			// 正确监听 showTosdata prop 的变化
			showTosdata: {
				handler(newVal) {
					this.showTos = newVal;
				},
				immediate: true, // 立即执行一次
				deep: false
			},

			Weight(newVal) {
				// 只有当手动输入框为空时，才自动同步Vuex的值到输入框
				if (this.manualWeight === '' && newVal > 0) {
					this.manualWeight = newVal.toString();
				}
			},
			// 监听父组件传入的userInfo变化，更新本地密码
			'userInfo.passWord': {
				handler(newVal) {
					this.localPassword = newVal || '';
				},
				immediate: true
			}
		},
		methods: {
			WeightStr(unit) {
				const weightInGrams = this.$store.state.weight.WeightStr;
				unit = (unit || '').toUpperCase();

				switch (unit) {
					case 'KG':
					case '千克':
						return (weightInGrams / 1000).toString() + 'kg';
					case 'G':
					case '克':
						return weightInGrams.toString() + 'g';
					case 'T':
					case '吨':
						return (weightInGrams / 1000000).toString() + 't';
					case 'LB':
					case '磅':
						return (weightInGrams / 453.592).toString() + 'lb';
					default:
						return (weightInGrams / 1000).toString() + 'kg'; // 默认返回千克
				}
			},
			// 获取用户显示文本
			getUserDisplayText(user) {
				if (!user) return '';

				let displayText = user.userName;

				// 添加用户ID
				if (user.userId) {
					displayText += ` (ID:${user.userId})`;
				}

				// 添加部门信息
				if (user.deptName) {
					displayText += ` - ${user.deptName}`;
				}

				// 添加角色信息
				if (user.roleName) {
					displayText += ` - ${user.roleName}`;
				}

				return displayText;
			},

			// 获取分配的用户列表
			queryAllocatedList() {
				if (this.loading) return;

				this.loading = true;
				getAllocatedList().then(res => {
					console.log('获取用户列表:', res);
					if (res.code === 200 && res.rows) {
						this.userList = res.rows.map(item => {
							return {
								userId: item.userId,
								userName: item.userName,
								passWord: '' // 初始化密码为空
							}
						});

						// 初始化选中的用户
						this.initSelectedUser();
					} else {
						this.userList = [];
						uni.showToast({
							title: '获取用户列表失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('获取用户列表错误:', err);
					this.userList = [];
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
				});
			},

			// 初始化选中的用户
			initSelectedUser() {
				if (this.userList && this.userList.length > 0) {
					// 如果有传入的userInfo，尝试匹配
					if (this.userInfo && this.userInfo.userName) {
						const matchedIndex = this.userList.findIndex(user =>
							user.userName === this.userInfo.userName
						);
						if (matchedIndex !== -1) {
							this.userIndex = matchedIndex;
							this.selectedUser = {
								...this.userList[matchedIndex]
							};
						} else {
							this.userIndex = 0;
							this.selectedUser = {
								...this.userList[0]
							};
						}
					} else {
						this.userIndex = 0;
						this.selectedUser = {
							...this.userList[0]
						};
					}

					// 总是重置密码
					this.localPassword = '';

					// 通知父组件用户已变更
					this.$emit('user-change', this.selectedUser);
					this.$emit('update:userInfo', {
						...this.selectedUser,
						passWord: '' // 清空密码
					});
				} else {
					// 如果没有用户数据，重置选中用户
					this.selectedUser = {};
					this.userIndex = 0;
					this.localPassword = '';
				}
			},

			// 用户选择变更
			onUserChange(e) {
				const index = parseInt(e.detail.value);
				if (index >= 0 && index < this.userList.length) {
					this.userIndex = index;
					this.selectedUser = {
						...this.userList[index]
					};
					// 重置密码
					this.localPassword = '';

					// 通知父组件用户已变更
					this.$emit('user-change', this.selectedUser);
					this.$emit('update:userInfo', {
						...this.selectedUser,
						passWord: '' // 清空密码
					});
				}
			},

			// 关闭弹窗
			close() {
				this.$emit('close');
			},

			// 确认操作
			confirm() {
				if (!this.hasWeightData) {
					uni.showToast({
						title: '请输入重量',
						icon: 'none'
					});
					return;
				}

				// 非管理员用户需要验证用户信息
				if (!this.adminUser && !this.isUserValid) {
					uni.showToast({
						title: '请选择用户并输入密码',
						icon: 'none'
					});
					return;
				}

				if (this.adminUser) {
					// 管理员用户：不包含用户信息
					const confirmData = {
						...this.infoData,
						weight: this.finalWeight,
						weightType: this.manualWeight !== '' ? 'manual' : 'auto'
					};
					this.$emit('confirm', confirmData);
				} else {
					// 普通用户：包含用户信息
					const confirmData = {
						...this.infoData,
						weight: this.finalWeight,
						weightType: this.manualWeight !== '' ? 'manual' : 'auto',
						// 包含更新后的用户信息
						userInfo: {
							...this.selectedUser,
							passWord: this.localPassword
						}
					};
					this.$emit('confirm', confirmData);
				}
			},


			// 确认操作
			confirm_status() {
				if (!this.hasWeightData) {
					uni.showToast({
						title: '请输入重量',
						icon: 'none'
					});
					return;
				}

				// 非管理员用户需要验证用户信息
				if (!this.adminUser && !this.isUserValid) {
					uni.showToast({
						title: '请选择用户并输入密码',
						icon: 'none'
					});
					return;
				}

				if (this.adminUser) {
					// 管理员用户：不包含用户信息
					const confirmData = {
						...this.infoData,
						weight: this.finalWeight,
						weightType: this.manualWeight !== '' ? 'manual' : 'auto'
					};
					this.$emit('confirms', confirmData);
				} else {
					// 普通用户：包含用户信息
					const confirmData = {
						...this.infoData,
						weight: this.finalWeight,
						weightType: this.manualWeight !== '' ? 'manual' : 'auto',
						// 包含更新后的用户信息
						userInfo: {
							...this.selectedUser,
							passWord: this.localPassword
						}
					};
					this.$emit('confirms', confirmData);
				}
			},



			// 手动输入重量
			onManualWeightInput(e) {
				const value = e.detail.value;
				this.manualWeight = value;

				// 实时更新Vuex中的重量值
				if (this.realtimeUpdate && value !== '') {
					const weightValue = parseFloat(value);
					if (!isNaN(weightValue)) {
						// 使用 weight store 的 mutation 更新重量
						
						console.log(`${String(weightValue)}${this.infoData.unitId}`,"`${String(weightValue)}${this.infoData.unitId}`");

						this.$store.dispatch('weight/updateWeight', `${String(weightValue)}${this.infoData.unitId}`)
						this.$store.dispatch('weight/updateWeightStr', `${String(weightValue)}${this.infoData.unitId}`)

					}
				}
			},

			// 密码输入处理
			onPasswordInput(e) {
				const value = e.detail.value;
				this.localPassword = value;


				// 或者单独发射密码更新事件
				this.$emit('password-change', value);
			},

			// 直接设置重量值的方法（供外部调用）
			setWeight(value) {
				const weightValue = parseFloat(value);
				if (!isNaN(weightValue)) {
					this.manualWeight = weightValue.toString();
					// 使用 weight store 的 mutation 更新重量
					this.$store.commit('weight/SET_WEIGHT', weightValue);
				}
			},

			// 设置密码的方法（供外部调用）
			setPassword(password) {
				this.localPassword = password;
				if (this.selectedUser) {
					this.selectedUser.passWord = password;
				}
				this.$emit('update:userInfo', {
					...this.selectedUser,
					passWord: password
				});
			},

			// 清除重量值
			clearWeight() {
				this.manualWeight = '';
				// 使用 weight store 的 mutation 更新重量
				this.$store.commit('weight/SET_WEIGHT', 0);
			},

			// 清除密码
			clearPassword() {
				this.localPassword = '';
				if (this.selectedUser) {
					this.selectedUser.passWord = '';
				}
				this.$emit('update:userInfo', {
					...this.selectedUser,
					passWord: ''
				});
			},

			// 刷新用户列表（供外部调用）
			refreshUserList() {
				this.queryAllocatedList();
			}
		}
	}
</script>


<style scoped>
	/* 遮罩层 */
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 998;
	}

	/* 弹窗容器 */
	.popup-container {
		position: fixed;
		top: 38%;
		left: 50%;
		transform: translate(-50%, -50%) scale(0.8);
		width: 90%;
		max-width: 900rpx;
		background: #fff;
		border-radius: 16rpx;
		z-index: 999;
		opacity: 0;
		transition: all 0.3s ease;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
	}

	.popup-show {
		transform: translate(-50%, -50%) scale(1);
		opacity: 1;
	}

	/* 弹窗内容 */
	.popup-content {
		padding: 40rpx;
	}

	/* 头部 */
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.close-icon {
		padding: 10rpx;
	}

	/* 信息展示区域 */
	.info-section {
		margin-bottom: 40rpx;
		max-height: 60vh;
		overflow-y: auto;
	}

	.info-group {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding: 0 10rpx;
	}

	.info-group-w {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding: 0 10rpx;
	}

	.info-group-input {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding: 0 10rpx;
	}

	.info-label {
		font-size: 28rpx;
		color: #666;
		flex-shrink: 0;
		width: 200rpx;
	}

	.info-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		text-align: right;
		flex: 1;
		word-break: break-all;
	}

	.info-label-u {
		font-size: 28rpx;
		color: #000000;
		flex-shrink: 0;
		width: 200rpx;
	}

	/* 用户选择容器 */
	.user-select-container {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 16rpx 20rpx;
		transition: all 0.3s;
	}

	.user-picker {
		flex: 1;
	}

	.picker-text {
		font-size: 32rpx;
		color: #0000ff;
		font-weight: 500;
		text-align: right;
		word-break: break-all;
	}

	.dropdown-icon {
		margin-left: 10rpx;
		flex-shrink: 0;
	}

	.info-value-w {
		font-size: 48rpx;
		color: #007AFF;
		font-weight: 800;
		text-align: right;
		flex: 1;
		word-break: break-all;
	}

	.info-value-s {
		font-size: 50rpx;
		text-align: right;
		flex: 1;
		word-break: break-all;
		color: #ff0000;
		text-align: right;
	}

	.info-value_aa {
		font-size: 28rpx;
		color: #b5b5b5;
		font-weight: 300;
		text-align: right;
		margin-right: 10rpx;
	}

	/* 输入框容器 */
	.input-container {
		flex: 1;
		display: flex;
		align-items: center;
		background: #f8f8f8;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		padding: 0 20rpx;
		height: 80rpx;
		transition: all 0.3s;
	}

	.input-container:focus-within {
		border-color: #007AFF;
		background: #fff;
		box-shadow: 0 0 10rpx rgba(0, 122, 255, 0.2);
	}

	.weight-input {
		flex: 1;
		height: 100%;
		font-size: 32rpx;
		color: #333;
		text-align: right;
	}

	.input-placeholder {
		font-size: 28rpx;
		color: #999;
		text-align: right;
	}

	.input-unit {
		font-size: 28rpx;
		color: #666;
		margin-left: 10rpx;
		flex-shrink: 0;
	}

	.negative-value {
		color: #FA5151;
		font-weight: bold;
	}

	/* 状态标签 */
	.status-badge {
		width: auto;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: normal;
	}

	.status-success {
		background: #E8F5E8;
		color: #07C160;
	}

	.status-default {
		background: #F0F0F0;
		color: #999;
	}

	/* 分割线 */
	.info-divider {
		height: 2rpx;
		background: #f0f0f0;
		margin: 30rpx 0;
	}

	/* 按钮组 */
	.button-group {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
	}

	.btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border: none;
		border-radius: 8rpx;
		font-size: 28rpx;
		transition: all 0.3s;
	}

	.btn-cancel {
		background: #f8f8f8;
		color: #666;
	}

	.btn-cancel:active {
		background: #e0e0e0;
	}

	.btn-confirm {
		background: #007AFF;
		color: #fff;
	}

	.btn-confirm-s {
		background: #ff3333;
		color: #fff;
	}

	.btn-confirm:active {
		background: #0056cc;
	}

	.btn-disabled {
		background: #ccc !important;
		color: #999 !important;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;
		color: #999;
	}

	.empty-state-c {}

	.empty-text {
		font-size: 28rpx;
		margin-top: 20rpx;
		color: #999;
	}

	/* 滚动条样式 */
	.info-section::-webkit-scrollbar {
		width: 4rpx;
	}

	.info-section::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 2rpx;
	}

	.info-section::-webkit-scrollbar-thumb {
		background: #c1c1c1;
		border-radius: 2rpx;
	}

	.info-section::-webkit-scrollbar-thumb:hover {
		background: #a8a8a8;
	}
</style>